package org.se.scut.pinterest.mina.codec.filte.coder.decoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.demux.MessageDecoderResult;
import org.se.scut.pinterest.mina.codec.coder.cxt.AllPictureTypeContext;
import org.se.scut.pinterest.mina.codec.coder.cxt.BaseContext;
import org.se.scut.pinterest.mina.codec.msg.AllPictureTypeMessage;

public class AllPictureTypeMessageDecoder extends BaseMessageDecoder {

	public AllPictureTypeMessageDecoder(){
		super(new AttributeKey(
			AllPictureTypeMessageDecoder.class, "context"), "apt");
	}
	
	@Override
	public MessageDecoderResult decode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		AllPictureTypeContext context = (AllPictureTypeContext)getContext(session);
		IoBuffer buffer = context.getInnerBuffer();
		int matchCount = context.getMatchCount();
		int lineNumber = context.getLineNumber();
		String symbol = context.getSymbol();
		String lastModifiedDate = context.getLastModifiedDate();
		byte b;
		while (in.hasRemaining()) {
			b = in.get();
			matchCount++;
			buffer.put(b);
			if (b == 10) {
				if (lineNumber == 0) {
					buffer.flip();
					symbol = buffer.getString(matchCount, DECODER);
					symbol = symbol.substring(0, symbol.length() - 1);
					matchCount = 0;
					buffer.clear();
					context.setSymbol(symbol);
				}
				if (lineNumber == 1) {
					buffer.flip();
					lastModifiedDate = buffer.getString(matchCount, DECODER);
					lastModifiedDate = lastModifiedDate.substring(0, lastModifiedDate.length() - 1);
					matchCount = 0;
					buffer.clear();
					context.setLastModifiedDate(lastModifiedDate);
					context.setLineNumber(lineNumber);
					break;
				}
				lineNumber++;
			}
			context.setMatchCount(matchCount);
			context.setLineNumber(lineNumber);
		}
		if (lineNumber == 1) {
			AllPictureTypeMessage msg = new AllPictureTypeMessage();
			msg.setSymbol(context.getSymbol());
			msg.setLastModifiedDate(context.getLastModifiedDate());
			out.write(msg);
			context.resetData();
			return MessageDecoderResult.OK;
		}else {
			return MessageDecoderResult.NEED_DATA;
		}
	}

	@Override
	public void finishDecode(IoSession session, ProtocolDecoderOutput out)
			throws Exception {
		
	}

	@Override
	public BaseContext getContext(IoSession session) {
		AllPictureTypeContext context = (AllPictureTypeContext)session.getAttribute(CONTEXT_KEY);
		if (context == null) {
			context = new  AllPictureTypeContext();
			session.setAttribute(CONTEXT_KEY, context);
		}
		return context;
	}

	

}
